//
//  JWGRScreenImagVC.m
//  test
//
//  Created by 李彦宏 on 2018/3/15.
//  Copyright © 2018年 朱圳. All rights reserved.
//未打款上传截图界面

#import "JWGRScreenImagVC.h"
#import <AVFoundation/AVFoundation.h>
#import "JWKCFeemodel.h"
#import "JWUserManager.h"
#import "JWGRUsermodel.h"

@interface JWGRScreenImagVC ()<UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (nonatomic, strong) JWKCFeemodel *model;
@property (nonatomic, strong) JWGRUsermodel *Gmodel;
@property (nonatomic, strong) UIImagePickerController *picker;

@end

@implementation JWGRScreenImagVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.Gmodel=[JWUserManager Gme];
    self.model=self.UPArry[0];
 
    //rightNavBtn
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.contentHorizontalAlignment=UIControlContentHorizontalAlignmentRight;
    [rightBtn setFrame:CGRectMake(0, 0, 40, 44)];
    [rightBtn setTitle:@"提交" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    rightBtn.titleLabel.font=[UIFont systemFontOfSize:15];
    [rightBtn addTarget:self action:@selector(rightBtnClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    
    self.view.backgroundColor=[UIColor whiteColor];
    [self setUI];
}
-(void)rightBtnClick{
    if (self.ImageView.image == nil) return;
    // 1.创建一个管理者
    
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    
    mgr = [AFHTTPSessionManager manager];
    [mgr setResponseSerializer:[AFJSONResponseSerializer new]];
    [mgr.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    mgr.requestSerializer.timeoutInterval = 30.0f;
    [mgr.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    [mgr.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/xml",@"text/css",@"text/plain",@"form-data",@"x-www-form-urlencoded",@"application/x-www-form-urlencoded",@"image/jpeg",@"image/png", nil]];
    NSDictionary *dic=@{@"jwid":JWid,
                        @"jwpassword":JWpassword,
                        @"yid":self.model.ID,
                        };
    
    // 2.发送一个请求
    //    NSString *url = @"http://192.168.15.172:8080/MJServer/upload";//上传地址
    [mgr POST:JW_KCUppict parameters:dic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSData *fileData = UIImageJPEGRepresentation(self.ImageView.image, 1.0);
        //系统当前时间
        NSDate *date=[NSDate date];
        NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        NSString *datestr=[formatter stringFromDate:date];
        NSString *filename = [NSString stringWithFormat:@"%@.jpg",datestr];
        [formData appendPartWithFileData:fileData name:@"files" fileName:filename mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"--uploadProgress--%@", uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSLog(@"--responseObject--%@", responseObject);
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.navigationController popViewControllerAnimated:YES];
        });
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"--error--%@", error);
    }];
    NSLog(@"上传成功");
}
-(void)setUI{
  #pragma -mark ————————————课酬信息————————————————————
    UILabel *lb1=[[UILabel alloc] init];
    [lb1 setBackgroundColor:[UIColor clearColor]];
    [lb1 setTextColor:[UIColor blackColor]];
    [lb1 setFont:[UIFont systemFontOfSize:15]];
    lb1.textAlignment=NSTextAlignmentLeft;
    lb1.text=@"学生:";
    [self.view addSubview:lb1];
    lb1.frame = CGRectMake(20, ScreenHeight/3-ScreenHeight*0.2222, 45, ScreenHeight/18);
    //学员姓名
    UILabel *Sname=[[UILabel alloc] init];
    [Sname setBackgroundColor:[UIColor clearColor]];
    [Sname setTextColor:[UIColor blackColor]];
    [Sname setFont:[UIFont systemFontOfSize:15]];
    Sname.textAlignment=NSTextAlignmentLeft;
    Sname.text=self.model.sname;
    [self.view addSubview:Sname];
    Sname.frame = CGRectMake(70, ScreenHeight/3-ScreenHeight*0.2222, 80, ScreenHeight/18);
    
    UILabel *lb2=[[UILabel alloc] init];
    [lb2 setBackgroundColor:[UIColor clearColor]];
    [lb2 setTextColor:[UIColor blackColor]];
    [lb2 setFont:[UIFont systemFontOfSize:15]];
    lb2.textAlignment=NSTextAlignmentLeft;
    lb2.text=@"打款帐号:";
    [self.view addSubview:lb2];
    lb2.frame = CGRectMake(20, ScreenHeight/3-ScreenHeight/6, 80, ScreenHeight/18);
    //打款帐号：
    UILabel *PayNumb=[[UILabel alloc] init];
    [PayNumb setBackgroundColor:[UIColor clearColor]];
    [PayNumb setTextColor:[UIColor blackColor]];
    [PayNumb setFont:[UIFont systemFontOfSize:15]];
    PayNumb.textAlignment=NSTextAlignmentLeft;
    PayNumb.text=self.Gmodel.moneynumber;
    [self.view addSubview:PayNumb];
    PayNumb.frame = CGRectMake(105, ScreenHeight/3-ScreenHeight/6, 150, ScreenHeight/18);
    
    
    UILabel *lb3=[[UILabel alloc] init];
    [lb3 setBackgroundColor:[UIColor clearColor]];
    [lb3 setTextColor:[UIColor blackColor]];
    [lb3 setFont:[UIFont systemFontOfSize:15]];
    lb3.textAlignment=NSTextAlignmentLeft;
    lb3.text=@"上课时间:";
    [self.view addSubview:lb3];
    lb3.frame = CGRectMake(20, ScreenHeight/3-ScreenHeight/9, 80, ScreenHeight/18);
    //上课时间
    UILabel *ClassTime=[[UILabel alloc] init];
    [ClassTime setBackgroundColor:[UIColor clearColor]];
    [ClassTime setTextColor:[UIColor blackColor]];
    [ClassTime setFont:[UIFont systemFontOfSize:15]];
    ClassTime.textAlignment=NSTextAlignmentLeft;
    //    上课时间显示
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
    [dateFormatter setDateFormat:@"yyyy-MM-dd"]; //设定时间的格式
    NSArray *p=[[Utility getDateStringWithTimeStr:_model.starttime] componentsSeparatedByString:@" "];
    NSArray *p2=[[Utility getDateStringWithTimeStr:_model.endtime] componentsSeparatedByString:@" "];
//    NSLog(@"分割后的字符串：%@",p[1]);
//     NSLog(@"分割后的字符串：%@",p2[1]);
    ClassTime.text = [NSString stringWithFormat:@"%@ %@-%@",p[0],p[1],p2[1]];
    [self.view addSubview:ClassTime];
    ClassTime.frame = CGRectMake(105, ScreenHeight/3-ScreenHeight/9, ScreenWidth-105, ScreenHeight/18);
    
    UILabel *lb4=[[UILabel alloc] init];
    [lb4 setBackgroundColor:[UIColor clearColor]];
    [lb4 setTextColor:[UIColor blackColor]];
    [lb4 setFont:[UIFont systemFontOfSize:15]];
    lb4.textAlignment=NSTextAlignmentLeft;
    lb4.text=@"单价:";
    [self.view addSubview:lb4];
    lb4.frame = CGRectMake(130, ScreenHeight/3-ScreenHeight/18, 45, ScreenHeight/18);
    //单价
    UILabel *price=[[UILabel alloc] init];
    [price setBackgroundColor:[UIColor clearColor]];
    [price setTextColor:[UIColor blackColor]];
    [price setFont:[UIFont systemFontOfSize:15]];
    price.textAlignment=NSTextAlignmentLeft;
    price.text=self.model.sprice;
    [self.view addSubview:price];
    price.frame =  CGRectMake(175, ScreenHeight/3-ScreenHeight/18, 40, ScreenHeight/18);
    
    
    
    UILabel *lb5=[[UILabel alloc] init];
    [lb5 setBackgroundColor:[UIColor clearColor]];
    [lb5 setTextColor:[UIColor blackColor]];
    [lb5 setFont:[UIFont systemFontOfSize:15]];
    lb5.textAlignment=NSTextAlignmentLeft;
    lb5.text=@"时长(分):";
    [self.view addSubview:lb5];
    lb5.frame = CGRectMake(20, ScreenHeight/3-ScreenHeight/18, 65, ScreenHeight/18);
    //时长
    UILabel *TimeLong=[[UILabel alloc] init];
    [TimeLong setBackgroundColor:[UIColor clearColor]];
    [TimeLong setTextColor:[UIColor blackColor]];
    [TimeLong setFont:[UIFont systemFontOfSize:15]];
    TimeLong.textAlignment=NSTextAlignmentLeft;
    double sc = ([_model.endtime doubleValue] - [_model.starttime doubleValue]);
    TimeLong.text = [NSString stringWithFormat:@"%.f",sc/60];
    [self.view addSubview:TimeLong];
    TimeLong.frame =  CGRectMake(85, ScreenHeight/3-ScreenHeight/18, 40, ScreenHeight/18);
    
    
    
    UILabel *lb6=[[UILabel alloc] init];
    [lb6 setBackgroundColor:[UIColor clearColor]];
    [lb6 setTextColor:[UIColor blackColor]];
    [lb6 setFont:[UIFont systemFontOfSize:15]];
    lb6.textAlignment=NSTextAlignmentLeft;
    lb6.text=@"课酬:";
    [self.view addSubview:lb6];
    lb6.frame = CGRectMake(20, ScreenHeight/3, 45, ScreenHeight/18);
    //课酬
    UILabel *KCmoney=[[UILabel alloc] init];
    [KCmoney setBackgroundColor:[UIColor clearColor]];
    [KCmoney setTextColor:[UIColor blackColor]];
    [KCmoney setFont:[UIFont systemFontOfSize:15]];
    KCmoney.textAlignment=NSTextAlignmentLeft;
    
    NSInteger Sprice=[_model.sprice doubleValue];

    KCmoney.text=[NSString stringWithFormat:@"%.f",sc/3600*Sprice];
    [self.view addSubview:KCmoney];
    KCmoney.frame = CGRectMake(70, ScreenHeight/3, 50, ScreenHeight/18);
    
    
#pragma -mark ————————————课程内容UI——————————————————————————
    UILabel *KCtitle=[[UILabel alloc] init];
    [KCtitle setBackgroundColor:[UIColor clearColor]];
    [KCtitle setTextColor:[UIColor blackColor]];
    [KCtitle setFont:[UIFont systemFontOfSize:16]];
    KCtitle.textAlignment=NSTextAlignmentCenter;
    KCtitle.text=@"课程内容";
    [self.view addSubview:KCtitle];
    KCtitle.frame = CGRectMake(ScreenWidth/2-40, ScreenHeight/3+ScreenHeight/18, 80, ScreenHeight/18);
#pragma -mark——————文本框———————————————————
    UITextView *teView=[[UITextView alloc]init];
    teView.frame=CGRectMake(20, ScreenHeight/3+ScreenHeight/9, ScreenWidth-40,ScreenHeight/3-ScreenHeight/9);
    
    
    if(self.model.content ==nil){
        teView.text=@"没有上课内容！！！";
    }else{
       teView.text=self.model.content;
    }
    // 设置文本字体
    teView.font = [UIFont fontWithName:@"Arial" size:16];
    teView.textColor=[UIColor blackColor];
    // 设置文本对齐方式
    teView.textAlignment = NSTextAlignmentLeft;
    //自动纠错
    teView.autocorrectionType=UITextAutocorrectionTypeNo;
    //外框
teView.layer.borderColor=dominantColor.CGColor;
    teView.layer.borderWidth=1;
    teView.layer.cornerRadius=5;
    //不自动大小写
teView.autocapitalizationType=UITextAutocorrectionTypeNo;
    // 设置return键样式
    teView.returnKeyType = UIReturnKeyDefault;
    // 设置是否可以拖动
    teView.scrollEnabled = NO;
    teView.editable=NO;
    [self.view addSubview:teView];
 #pragma -mark ———————打款截图UI————————————————————
    UILabel *ADDlbe=[[UILabel alloc] init];
    [ADDlbe setBackgroundColor:[UIColor clearColor]];
    [ADDlbe setTextColor:[UIColor blackColor]];
    [ADDlbe setFont:[UIFont systemFontOfSize:16]];
    ADDlbe.textAlignment=NSTextAlignmentCenter;
    ADDlbe.text=@"打款截图";
    [self.view addSubview:ADDlbe];
    ADDlbe.frame = CGRectMake(ScreenWidth/2-60, ScreenHeight*0.66, 80, ScreenHeight/15);
   
    UIButton *adBtn=[UIButton buttonWithType:UIButtonTypeContactAdd];
    adBtn.frame=CGRectMake(ScreenWidth/2+25, ScreenHeight*0.66, 35, ScreenHeight/15);
    self.AddBtn=adBtn;
    [adBtn addTarget:self action:@selector(AddBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:adBtn];
    
    UIImageView *ImageView=[[UIImageView alloc]init];
    ImageView.layer.cornerRadius=5;
    ImageView.layer.borderColor=dominantColor.CGColor;
    ImageView.layer.borderWidth=1;
    
    ImageView.frame=CGRectMake(20, ScreenHeight*0.66+ScreenHeight/15, ScreenWidth-40, ScreenHeight/3-30-ScreenHeight/15);
    ImageView.backgroundColor=[UIColor whiteColor];
    self.ImageView=ImageView;
    [self.view addSubview:ImageView];
}
-(void)AddBtn:(UIButton *)send
 
    {
        __block typeof (self) weak_self = self;
        
        _picker = [[UIImagePickerController alloc] init];
        _picker.delegate = self;
        _picker.allowsEditing = YES;
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择图片"
                                                                                 message:@""
                                                                          preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {}];
        UIAlertAction* fromPhotoAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault                                                                 handler:^(UIAlertAction * action) {
            weak_self.picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [weak_self presentViewController:weak_self.picker animated:YES completion:nil];
            NSLog(@"从相册选择");
        }];
        UIAlertAction* fromCameraAction = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDefault                                                             handler:^(UIAlertAction * action) {
            NSLog(@"相机");
            
            UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
            if(! [UIImagePickerController isSourceTypeAvailable:sourceType]){
                NSString *tips = @"相机不可用";
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:tips preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    NSLog(@"取消");
                }];
                UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    NSLog(@"确定");
                }];
                [alertController addAction:cancelAction];
                [alertController addAction:otherAction];
                [self presentViewController:alertController animated:YES completion:nil];
                return;
            }
            _picker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:_picker animated:YES completion:nil];
            if (![self getCameraRecordPermisson]) {
                NSString *tips = @"请在iPhone的“设置-隐私-相机”中允许访问相机";
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"无法使用相机" message:tips preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    NSLog(@"取消");
                }];
                UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    NSLog(@"确定");
                }];
                [alertController addAction:cancelAction];
                [alertController addAction:otherAction];
                [self presentViewController:alertController animated:YES completion:nil];
                
            }
            
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:fromCameraAction];
        [alertController addAction:fromPhotoAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
    
    
}
#pragma mark UIImagePickerControllerDelegate
//选择图或者拍照后的回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *orignalImage = [info objectForKey:UIImagePickerControllerOriginalImage];//原图
    UIImage *editedImage = [info objectForKey:UIImagePickerControllerEditedImage];//编辑后的图片
    
    _ImageView.image = editedImage;
    
    // 拍照后保存原图片到相册中
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera && orignalImage) {
        UIImageWriteToSavedPhotosAlbum(orignalImage, self, nil, NULL);
    }
    //上传照片
    [picker dismissViewControllerAnimated:YES completion:^{
//        if (editedImage) {
//            [self doUploadPhoto:editedImage];
//        }
    }];
}


//获得设备是否有访问相机权限
-(BOOL)getCameraRecordPermisson
{
    NSString * mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied)
    {
        return NO;
    }
    return YES;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
